package com.game.code;

//import java.util.logging.Logger;
//import java.util.logging.Level;

import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;
import org.jbox2d.dynamics.World;

import com.game.interfacesForImplementer.Canvas;

public class Ball {
	public static final float WORLD_PHYSICS_SIZE = 10;
	public static final float BALL_RADIUS = WORLD_PHYSICS_SIZE/50;
	public static final float BALL_SPEED = 15;
	public static final float FORBIDDEN_CORNERS_TO_AXIS_LESS_THAN = (float) (Math.PI/12);
	
	Body body;

	//Logger logger = Logger.getLogger("NameOfYourLogger");
	
	public Ball(World world){

		CircleShape shape = new CircleShape();
		shape.m_radius = BALL_RADIUS;

		FixtureDef fd = new FixtureDef();
		fd.shape = shape;
		fd.density = 0.2f;
		fd.restitution=1.0f;
		fd.friction=0.0f;
		
		
		BodyDef bd = new BodyDef();
		bd.type = BodyType.DYNAMIC;
		bd.position.set(0,-WORLD_PHYSICS_SIZE/2*4/5);
		body = world.createBody(bd);
		body.createFixture(fd);
		
		body.setUserData("ball");
	}


	public void onDraw(Canvas canvas) {

		RGB rgb = new RGB(255,255,255);
		
		Vec2 b=body.getPosition();
		float x=(b.x+WORLD_PHYSICS_SIZE/2)/WORLD_PHYSICS_SIZE*canvas.getWidth();
		float y=(b.y+WORLD_PHYSICS_SIZE/2)/WORLD_PHYSICS_SIZE*canvas.getHeight();
		float r_x=2*BALL_RADIUS/WORLD_PHYSICS_SIZE*canvas.getWidth();
		float r_y=2*BALL_RADIUS/WORLD_PHYSICS_SIZE*canvas.getHeight();

		canvas.rectangle((int)(x-r_x/2), (int)(y-r_y/2), (int)r_x, (int) r_y, rgb);
	}


	
	public void correctCornersAndVelocity() {
		Vec2 v=body.getLinearVelocity();

		v.normalize();

		float l=v.length();
		if(l!=0)
		  {
			if( Math.abs(v.x/l)<Math.sin(FORBIDDEN_CORNERS_TO_AXIS_LESS_THAN)){
				//logger.log(Level.SEVERE, "FORBIDDEN BALL CORNER! l="+l+" v.x="+v.x+" v.y="+v.y+" sin="+Math.abs(v.x/l));
				v.x=(float) (Math.signum(v.x)*Math.sin(Math.PI/4));
				}
			if( Math.abs(v.y/l)<Math.sin(FORBIDDEN_CORNERS_TO_AXIS_LESS_THAN)){
				//logger.log(Level.SEVERE, "FORBIDDEN BALL CORNER! l="+l+" v.x="+v.x+" v.y="+v.y+" sin="+Math.abs(v.y/l));
				v.y=(float) (Math.signum(v.y)*Math.sin(Math.PI/4));
				}
		  }
		
		//normalize to correct velocity
		body.setLinearVelocity(v.mul(BALL_SPEED));
		
	}
}
